package com.yc.springmvc;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//类型转换
public class SqlDateConvertor implements Converter <String, Date>{
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat format3 = new SimpleDateFormat("yyyy年MM月dd日");


    @Override
    public Date convert(String s) {
        //yyyy-MM-dd HH:mm:ss    yyyy/MM/dd   yyyy年MM月dd日
        if (s.matches("\\d{4}-\\d{2}-\\d{2}.*")){
            s = s.substring(0,10);
            return parse(s,format1);
        }else if (s.matches("\\d{4}/\\d{2}/\\d{2}.*")){
            s = s.substring(0,10);
            return parse(s,format2);
        }else if (s.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")){
            s = s.substring(0,11);
            return parse(s,format3);
        }
        throw new UnsupportedOperationException("不支持的日期类型" + s);
    }

    private Date parse(String s,SimpleDateFormat sdf){
        try {
            Date parse = sdf.parse(s);
            return new Date(parse.getTime());
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误", e);
        }
    }
}
